package io.finer.erp.jeecg.bas.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import io.finer.erp.jeecg.bas.dto.MaterialDTO;
import io.finer.erp.jeecg.bas.entity.*;
import io.finer.erp.jeecg.bas.service.*;
import io.finer.erp.jeecg.bas.util.*;
import io.finer.erp.jeecg.bas.vo.PrintQzOrderVO;
import io.finer.erp.jeecg.bas.vo.SeperateMesVO;
import io.finer.erp.jeecg.bas.vo.ZrkParametersVO;
import io.finer.erp.jeecg.bas.vo.ZrkQzOrderPage;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.entity.StkIoBillEntry;
import io.finer.erp.jeecg.stock.entity.StkPickUpBill;
import io.finer.erp.jeecg.stock.entity.StkPickUpEntry;
import io.finer.erp.jeecg.stock.mapper.StkIoBillEntryMapper;
import io.finer.erp.jeecg.stock.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.MaterialConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TestDTO2;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 分切/切张单
 * @Author: jeecg-boot
 * @Date:   2020-10-14
 * @Version: V1.0
 */
@Api(tags="分切/切张单")
@RestController
@RequestMapping("/bas/zrkQzOrder")
@Slf4j
public class ZrkQzOrderController {
	@Autowired
	private IZrkQzOrderService zrkQzOrderService;
	@Autowired
	private IZrkQzOrdeDetailService zrkQzOrdeDetailService;
	@Autowired
	private IZrkParametersService zrkParametersService;
	@Autowired
	private IStkPickUpBillService pickUpBillService;
	@Autowired
	private IErpSysService erpSysService;
	@Autowired
	private IZrkOrderProcessService orderProcessService;

	@Autowired
	private IBasMaterialService basMaterialService;
	@Autowired
	private IBasMaterialTempService basMaterialTempService;
	@Autowired
	private IBasMaterialCategoryService basMaterialCategoryService;
	
	@Autowired
	private IZzDeviceTypeService zzDeviceTypeService;
	@Autowired
	private IZzShoporderService orderService;

	@Autowired
	private IStkPickUpEntryService pickUpEntryService;
	@Autowired
	private IStkInventoryService stkInventoryService;
	@Autowired
	private IStkIoBillService stkIoBillService;
	@Autowired
	private IStkIoBillEntryService stkIoBillEntryService;
	@Autowired
	private StkIoBillEntryMapper  stkIoBillEntryMapper;
	@Autowired
	private ISysBaseAPI basApi;

	/**
	 * 分页列表查询
	 *
	 * @param zrkQzOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "分切/切张单-分页列表查询")
	@ApiOperation(value="分切/切张单-分页列表查询", notes="分切/切张单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ZrkQzOrder zrkQzOrder,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) {
		QueryWrapper<ZrkQzOrder> queryWrapper = QueryGenerator.initQueryWrapper(zrkQzOrder, req.getParameterMap());
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();//获取登录用户信息
		//admin可以查看所有，此处排除admin用户的权限检测
		boolean flag = true;
//		if(!sysUser.getUsername().equals("admin")) {
//			flag = false;
//		}
		List<ErpSysRole> roleList = this.erpSysService.getRoleByUserId(sysUser.getId());
		if(null != roleList && roleList.size() > 0) {
			for (ErpSysRole erpSysRole : roleList) {
				if("admin".equals(erpSysRole.getRoleCode()) || "productTeamLead".equals(erpSysRole.getRoleCode()) || "productLead".equals(erpSysRole.getRoleCode())) {
					flag = false;
					break;
				}
			}
		}
		if(flag) {
			queryWrapper.and(wrapper -> wrapper.like("operator_users", sysUser.getId()));
		} 
		Page<ZrkQzOrder> page = new Page<ZrkQzOrder>(pageNo, pageSize);
		IPage<ZrkQzOrder> pageList = zrkQzOrderService.page(page, queryWrapper);
		return Result.ok(pageList);
	}


	@AutoLog(value = "分切/切张单-分页列表查询")
	@ApiOperation(value="分切/切张单-分页列表查询", notes="分切/切张单-分页列表查询")
	@GetMapping(value = "/listProcessFQ")
	public Result<?> listProcessFQ(ZrkQzOrder zrkQzOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ZrkQzOrder> queryWrapper = new QueryWrapper<>();
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();//获取登录用户信息
		//admin可以查看所有，此处排除admin用户的权限检测
		boolean flag = true;
//		if(!sysUser.getUsername().equals("admin")) {
//			flag = false;
//		}
		List<ErpSysRole> roleList = this.erpSysService.getRoleByUserId(sysUser.getId());
		if(null != roleList && roleList.size() > 0) {
			for (ErpSysRole erpSysRole : roleList) {
				if("admin".equals(erpSysRole.getRoleCode()) || "productTeamLead".equals(erpSysRole.getRoleCode()) || "productLead".equals(erpSysRole.getRoleCode())) {
					flag = false;
					break;
				}
			}
		}
		String operatorUsers = null;
		if(flag) {
//			queryWrapper.and(wrapper -> wrapper.like("operator_users", sysUser.getId()));
			operatorUsers = sysUser.getId();
			zrkQzOrder.setOperatorUsers(operatorUsers);
		}else {
			if(StringUtils.isNotBlank(zrkQzOrder.getOperatorUsers())) {
				String[] userNames = StringUtils.split(zrkQzOrder.getOperatorUsers(), ",");
				List<LoginUser> userList = basApi.queryUserByNames(userNames);
				StringBuffer buffer = new StringBuffer();
				if(userList!=null && userList.size()>0) {
					for(LoginUser user:userList) {
						buffer.append(user.getId());
						buffer.append(",");
					}
					zrkQzOrder.setOperatorUsers(buffer.toString().substring(0, buffer.length()-1));
//					queryWrapper.like("operator_users", zrkQzOrder.getOperatorUsers());
				}
			}
		}
//		String column = req.getParameter("column");
//		String order = req.getParameter("order");
//		if(StringUtils.isNotBlank(column) && StringUtils.isNotBlank(order)) {
//			zrkQzOrder.setColumn(column);
//			zrkQzOrder.setOrder(order);
//		}
//		if(StringUtils.equals("createTime", column)) {
//			zrkQzOrder.setColumn(null);
//			zrkQzOrder.setOrder(null);
//		}
//		queryWrapper.eq("process_id", MaterialConstant.PROCESS_PART);
		Page<ZrkQzOrder> page = new Page<ZrkQzOrder>(pageNo, pageSize);
		IPage<ZrkQzOrder> pageList = zrkQzOrderService.getPageFQList(page, zrkQzOrder);
		return Result.ok(pageList);
	}

	@AutoLog(value = "切张单-分页列表查询")
	@ApiOperation(value="切张单-分页列表查询", notes="切张单-分页列表查询")
	@GetMapping(value = "/listProcessQZ")
	public Result<?> queryPageListProcessQz(ZrkQzOrder zrkQzOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ZrkQzOrder> queryWrapper = new QueryWrapper<>();
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();//获取登录用户信息
		//admin可以查看所有，此处排除admin用户的权限检测
		boolean flag = true;
//		if(!sysUser.getUsername().equals("admin")) {
//			flag = false;
//		}
		List<ErpSysRole> roleList = this.erpSysService.getRoleByUserId(sysUser.getId());
		if(null != roleList && roleList.size() > 0) {
			for (ErpSysRole erpSysRole : roleList) {
				if("admin".equals(erpSysRole.getRoleCode()) || "productTeamLead".equals(erpSysRole.getRoleCode()) || "productLead".equals(erpSysRole.getRoleCode())) {
					flag = false;
					break;
				}
			}
		}
		String operatorUsers = null;
		if(flag) {
//			queryWrapper.and(wrapper -> wrapper.like("operator_users", sysUser.getId()));
			operatorUsers = sysUser.getId();
			zrkQzOrder.setOperatorUsers(operatorUsers);
		}else {
			if(StringUtils.isNotBlank(zrkQzOrder.getOperatorUsers())) {
				String[] userNames = StringUtils.split(zrkQzOrder.getOperatorUsers(), ",");
				List<LoginUser> userList = basApi.queryUserByNames(userNames);
				StringBuffer buffer = new StringBuffer();
				if(userList!=null && userList.size()>0) {
					for(LoginUser user:userList) {
						buffer.append(user.getId());
						buffer.append(",");
					}
					zrkQzOrder.setOperatorUsers(buffer.toString().substring(0, buffer.length()-1));
//					queryWrapper.and(wrapper -> wrapper.like("operator_users", zrkQzOrder.getOperatorUsers()));
				}
			}
		}
//		List<String> qz= new ArrayList<>();
//		qz.add(MaterialConstant.PROCESS_CUTTING_NORMAL);
//		qz.add(MaterialConstant.PROCESS_CUTTING_BIG);
//		queryWrapper.in("process_id",qz);
//		String column = req.getParameter("column");
//		String order = req.getParameter("order");
//		if(StringUtils.isNotBlank(column) && StringUtils.isNotBlank(order)) {
//			zrkQzOrder.setColumn(column);
//			zrkQzOrder.setOrder(order);
//		}
		Page<ZrkQzOrder> page = new Page<ZrkQzOrder>(pageNo, pageSize);
		IPage<ZrkQzOrder> pageList = zrkQzOrderService.getPageQZList(page, zrkQzOrder);
		return Result.ok(pageList);
	}



	@AutoLog(value = "复合单-分页列表查询")
	@ApiOperation(value="复合单-分页列表查询", notes="复合单-分页列表查询")
	@GetMapping(value = "/listProcess")
	public Result<?> queryPageFHList(ZrkQzOrder zrkQzOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ZrkQzOrder> queryWrapper = QueryGenerator.initQueryWrapper(zrkQzOrder, req.getParameterMap());
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();//获取登录用户信息
		//admin可以查看所有，此处排除admin用户的权限检测
		boolean flag = true;
//		if(!sysUser.getUsername().equals("admin")) {
//			flag = false;
//		}
		List<ErpSysRole> roleList = this.erpSysService.getRoleByUserId(sysUser.getId());
		if(null != roleList && roleList.size() > 0) {
			for (ErpSysRole erpSysRole : roleList) {
				if("admin".equals(erpSysRole.getRoleCode()) || "productTeamLead".equals(erpSysRole.getRoleCode()) || "productLead".equals(erpSysRole.getRoleCode())) {
					flag = false;
					break;
				}
			}
		}
		String operatorUsers = null;
		if(flag) {
//			queryWrapper.and(wrapper -> wrapper.like("operator_users", sysUser.getId()));
			operatorUsers = sysUser.getId();
			zrkQzOrder.setOperatorUsers(operatorUsers);
		}else {
			if(StringUtils.isNotBlank(zrkQzOrder.getOperatorUsers())) {
				String[] userNames = StringUtils.split(zrkQzOrder.getOperatorUsers(), ",");
				List<LoginUser> userList = basApi.queryUserByNames(userNames);
				StringBuffer buffer = new StringBuffer();
				if(userList!=null && userList.size()>0) {
					for(LoginUser user:userList) {
						buffer.append(user.getId());
						buffer.append(",");
					}
					zrkQzOrder.setOperatorUsers(buffer.toString().substring(0, buffer.length()-1));
				}
			}
		}
//		queryWrapper.eq("process_id", MaterialConstant.PROCESS_COMPOUND).orderByAsc("sort");
		Page<ZrkQzOrder> page = new Page<ZrkQzOrder>(pageNo, pageSize);
//		IPage<ZrkQzOrder> pageList = zrkQzOrderService.page(page, queryWrapper);
//		Integer isFinish = zrkQzOrder.getIsFinish();
//		String machineId = zrkQzOrder.getMachineId();
//		String glue = zrkQzOrder.getGlue();
		IPage<ZrkQzOrder> pageList = zrkQzOrderService.getPageList(page, zrkQzOrder);
		return Result.ok(pageList);
	}



	@AutoLog(value = "制胶单-分页列表查询")
	@ApiOperation(value="制胶单-分页列表查询", notes="制胶单-分页列表查询")
	@GetMapping(value = "/listProcessZj")
	public Result<?> queryPageZJList(ZrkQzOrder zrkQzOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ZrkQzOrder> queryWrapper = QueryGenerator.initQueryWrapper(zrkQzOrder, req.getParameterMap());
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();//获取登录用户信息
		//admin可以查看所有，此处排除admin用户的权限检测
		boolean flag = true;
		List<ErpSysRole> roleList = this.erpSysService.getRoleByUserId(sysUser.getId());
		if(null != roleList && roleList.size() > 0) {
			for (ErpSysRole erpSysRole : roleList) {
				if("admin".equals(erpSysRole.getRoleCode()) || "productTeamLead".equals(erpSysRole.getRoleCode()) || "productLead".equals(erpSysRole.getRoleCode())) {
					flag = false;
					break;
				}
			}
		}
		if(flag) {
			queryWrapper.and(wrapper -> wrapper.like("operator_users", sysUser.getId()));
		}
		queryWrapper.eq("process_id", MaterialConstant.PROCESS_ZJ);
		Page<ZrkQzOrder> page = new Page<ZrkQzOrder>(pageNo, pageSize);
		IPage<ZrkQzOrder> pageList = zrkQzOrderService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	@AutoLog(value = "上调")
	@ApiOperation(value="上调", notes="上调")
	@PutMapping(value = "/updateSortAsc")
	public Result<?> updateSortAsc(@RequestBody ZrkQzOrder zrkQzOrder) {
		return zrkQzOrderService.updateSortAsc(zrkQzOrder);
	}

	@AutoLog(value = "下调")
	@ApiOperation(value="下调", notes="下调")
	@PutMapping(value = "/updateSortDesc")
	public Result<?> updateSortDesc(@RequestBody ZrkQzOrder zrkQzOrder) {
		return zrkQzOrderService.updateSortDesc(zrkQzOrder);
	}

	@AutoLog(value = "判断是否有权限操作")
	@ApiOperation(value="判断是否有权限操作", notes="判断是否有权限操作")
	@GetMapping(value = "/canOpen")
	public Result<?> canOpen() {
		boolean flag = true;
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();//获取登录用户信息
		if(sysUser.getUsername().equals("admin")) {
			flag = true;
		}else if(!sysUser.getUsername().equals("admin")){
			flag=false;
		}else {
			List<ErpSysRole> roleList = this.erpSysService.getRoleByUserId(sysUser.getId());
			if(null != roleList && roleList.size() > 0) {
				for (ErpSysRole erpSysRole : roleList) {
					if("productTeamLead".equals(erpSysRole.getRoleCode()) || "productLead".equals(erpSysRole.getRoleCode())) {
						flag = false;
						break;
					}
				}
			}
		}
		return Result.ok(flag);
		
	}


	/**
	 *   添加
	 *
	 * @param zrkQzOrderPage
	 * @return
	 */
	@AutoLog(value = "分切/切张单-添加")
	@ApiOperation(value="分切/切张单-添加", notes="分切/切张单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ZrkQzOrderPage zrkQzOrderPage) {
		ZrkQzOrder zrkQzOrder = new ZrkQzOrder();
		BeanUtils.copyProperties(zrkQzOrderPage, zrkQzOrder);
		zrkQzOrderService.saveMain(zrkQzOrder, zrkQzOrderPage.getZrkQzOrdeDetailList());
		return Result.ok("添加成功！");
	}

	/**
	 *   合并切张单--生成合并信息
	 *
	 * @param zrkQzOrderPage
	 * @return
	 */
	@AutoLog(value = "合并切张单--生成合并信息")
	@ApiOperation(value="合并切张单--生成合并信息", notes="合并切张单--生成合并信息")
	@PostMapping(value = "/mergeReal")
	public Result<?> mergeReal(@RequestBody ZrkQzOrderPage zrkQzOrderPage){
		String ids=zrkQzOrderPage.getId();
		//获取分组编号
		String groupId=this.basApi.getNoByCode("qz_order_group_no");
		//合并分切参数数量
		Map<Double,Integer> map=new HashMap<Double,Integer>();
		//拆分
		if(null!=ids&&!ids.equals("")) {
			String [] tmp=ids.split(",");
			if(null!=tmp&&tmp.length>0) {
				for(int i=0;i<tmp.length;i++) {
					//查询
					ZrkQzOrder zoo=zrkQzOrderService.getById(tmp[i]);
					String [] tm=zoo.getSpecs().split("\\+");
					if(null!=tm&&tm.length>0) {
						for(String s:tm) {
							try {
								Integer num=map.get(Double.parseDouble(s));
								map.put(Double.parseDouble(s), zoo.getProductNum().intValue()+num);
							}catch(Exception e) {
								map.put(Double.parseDouble(s), zoo.getProductNum().intValue());
							}
						}
					}
					zoo.setUniteInfo(zrkQzOrderPage.getUniteInfo());
					zoo.setTailings(zrkQzOrderPage.getTailings());
					zoo.setIsUnite(1);//是否合并
					zoo.setMasterbatc(zrkQzOrderPage.getZrkAmt());//记录母料宽度
					zoo.setOrderGroup(groupId);
					zrkQzOrderService.updateById(zoo);//合并信息
				}
			}
			String str="";
			//更新合并后的分切参数
			if(null!=map&&map.size()>0) {
				for(Double key : map.keySet()){
				    Integer value = map.get(key);
				    System.out.println(key+":"+value);
				    if(str.equals("")) {
				    	str=key+"*"+value;
				    }else {
				    	str+="+"+key+"*"+value;
				    }
				}
			}
			if(null!=tmp&&tmp.length>0) {
				for(int i=0;i<tmp.length;i++) {
  					 //更新合并后的分切参数
					ZrkQzOrder zoo=zrkQzOrderService.getById(tmp[i]);
					zoo.setUniteParams(str);
					zrkQzOrderService.updateById(zoo);//合并分切参数
				}
			}
		}
		return Result.ok("合并成功！");
	}

	/**
	 *   合并切张单
	 *
	 * @param zrkQzOrderPage
	 * @return
	 */
	@AutoLog(value = "合并切张单")
	@ApiOperation(value="合并切张单", notes="合并切张单")
	@PostMapping(value = "/merge")
	public Result<?> merge(@RequestBody ZrkQzOrderPage zrkQzOrderPage) {
		//声明所有方案的字符串串
		//		String targetStr="";
		//合并逻辑为前端选择要合并的切张/分切单，然后通过id传递到后台
		String ids=zrkQzOrderPage.getId();
		//		Map<String,Object> map=new HashMap<String,Object>();
		List<TestDTO2> specList=new ArrayList<TestDTO2>(); 
		//		List<Double> speList=new ArrayList<Double>();
		List<String> categoryList=new ArrayList<String>();
		List<Integer> longList=new ArrayList<Integer>();
		//判断用户所选是否都为分切工序
		Map<String,String> fqMap=new HashMap<String,String>();
		//		List<Double> lis=new ArrayList<Double>();
		int k=0;
		//拆分
		if(null!=ids&&!ids.equals("")) {
			String [] tmp=ids.split(",");
			if(null!=tmp&&tmp.length>0) {
				for(int i=0;i<tmp.length;i++) {
					//查询
					ZrkQzOrder zoo=zrkQzOrderService.getById(tmp[i]);
					if(null!=zoo) {
						//判断工序
						ZzDeviceType process=zzDeviceTypeService.getById(zoo.getProcessId());
						if(null!=process) {
							if(process.getDeviceTpyeName().equals("分切")) {
								fqMap.put(zoo.getId(), "分切");
							}
						}
					}
					if(null!=zoo) {
						BasMaterial bm=basMaterialService.getById(zoo.getMaterialId());
						if(null!=bm) {
							//记录物料分类ID，用来判断合并的所有单据是否为同一物料
							categoryList.add(bm.getCategoryId());
						}
						//记录所有单据长度，用来判断合并的所有单据是否为同一长度的物料
						longList.add(zoo.getZrkAmt());
						//处理规格
						String specs=zoo.getSpecs();
						if(null!=specs&&!specs.equals("")) {
							String [] tm=specs.split("\\+");
							if(null!=tm&&tm.length>0) {
								for(int j=0;j<tm.length;j++) {
									//将所有可能加入list中
									TestDTO2 td=new TestDTO2();
									td.setId((j+1)+"");
									td.setNum(zoo.getProductNum().doubleValue());
									td.setWidth(Double.parseDouble(tm[j]));
									specList.add(td);
								}
							}
						}
					}else {
						return Result.error("未查询到单据信息");
					}
				}
				boolean isRepeat =1 == new HashSet<String>(categoryList).size();
				boolean isRepeat2 =1 == new HashSet<Integer>(longList).size();
				boolean isAllFq=tmp.length== fqMap.size();
				if(isAllFq) {
					if(isRepeat&&isRepeat2) {
						Map<Double,Integer> tarMap=new HashMap<Double,Integer>();
						//可以合并获取方案,拼接数组
						if(null!=specList&&specList.size()>0) {
							for(TestDTO2 tdd:specList) {
								try {
									Integer num=tarMap.get(tdd.getWidth()).intValue();
									k+=num;
									tarMap.put(tdd.getWidth(), (num+tdd.getNum().intValue()));
								}catch(Exception e) {
									k+=tdd.getNum().intValue();
									tarMap.put(tdd.getWidth(), tdd.getNum().intValue());
								}
							}
						}
						String [] arr=new String [k-1];
						int k2=0;
						//遍历map拼接数组
						for(Double key : tarMap.keySet()){
							Integer value = tarMap.get(key);
							System.out.println(key+":"+value);
							for(int i=0;i<value;i++) {
								arr[k2]=key+"";
								k2++;
							}
						}
						//调用获取方案，得到map，correct 正确的组合（可能会有重复） uncorrect 剩余参数
						Map<String,String> resultMap=new GetSexUtils().getSexFA(arr, zrkQzOrderPage.getZrkAmt().doubleValue());
						//数组重置
						Map<String,Integer> coMap=new HashMap<String,Integer>();
						//判断正确组合是否有重复
						if(null!=resultMap&&resultMap.size()>0) {
							String correct=resultMap.get("correct");
							String uncorrect=resultMap.get("uncorrect");
							String [] ftmp=correct.split(";");
							if(null!=ftmp&&ftmp.length>0) {
								for(String s:ftmp) {
									if(null!=s&&!s.equals("")) {
										try {
											Integer nu=coMap.get(s);
											coMap.put(s, nu+1);
										}catch(Exception e) {
											coMap.put(s, 1);
										}
									}
								}
							}
							//处理剩余组合
							Map<String,Integer> coMap2=new HashMap<String,Integer>();
							if(null!=uncorrect&&!uncorrect.equals("")) {
								String[] lefArr=uncorrect.split(",");
								if(null!=lefArr&&lefArr.length>0) {
									Map<String,String> resulMap=new GetSexUtils2().getSexFA(lefArr, zrkQzOrderPage.getZrkAmt().doubleValue());
									String correct2=resulMap.get("correct");
									String uncorrect2=resulMap.get("uncorrect");
									//								Map<Double,Integer> uncoMap2=new HashMap<Double,Integer>();
									String [] uncoTmp2=correct2.split(";");
									String [] conTmp3=uncorrect2.split(",");
									if(null!=resulMap&&resulMap.size()>0) {
										if(null!=uncoTmp2&&uncoTmp2.length>0) {
											for(String s:uncoTmp2) {
												if(null!=s&&!s.equals("")) {
													try {
														Integer num=coMap2.get(s);
														coMap2.put(s, num+1);
													}catch(Exception e) {
														coMap2.put(s, 1);
													}
												}
											}
										}
										if(null!=conTmp3&&conTmp3.length>0) {
											for(String s:conTmp3) {
												if(null!=s&&!s.equals("")) {
													try {
														Integer num=coMap2.get(s);
														coMap2.put(s, num+1);
													}catch(Exception e) {
														coMap2.put(s, 1);
													}
												}
											}
										}
									}
								}
							}
							//合并所有方案并计算尾料
							List<ResponseFA> list=new ArrayList<ResponseFA>();
							if(null!=coMap&&coMap.size()>0) {
								for(String key : coMap.keySet()){
									Integer value = coMap.get(key);
									System.out.println(key+":"+value);
									ResponseFA rfa=new ResponseFA();
									rfa.setFa(key);
									rfa.setNum(value);
									String [] tt=key.split(",");
									rfa.setTds(1);
									rfa.setDs((tt.length-1)+2);
									rfa.setWL(false);
									rfa.setWlWidth(0.0);
									list.add(rfa);
								}
							}
							if(null!=coMap2&&coMap2.size()>0) {
								for(String key : coMap2.keySet()){
									Integer value = coMap2.get(key);
									System.out.println(key+":"+value);
									ResponseFA rfa=new ResponseFA();
									rfa.setFa(key);
									rfa.setNum(value);
									String [] tt=key.split(",");
									double kk=0.0;
									if(null!=tt&&tt.length>0) {
										for(String ss:tt) {
											if(null!=ss&&!ss.equals("")) {
												kk+=Double.parseDouble(ss);
											}
										}
									}
									Double lef=zrkQzOrderPage.getZrkAmt().doubleValue()-(kk);
									rfa.setTds(1);
									rfa.setDs((tt.length-1)+2);
									rfa.setWL(true);
									rfa.setWlWidth(lef);
									list.add(rfa);
								}
							}
							correct="";
							uncorrect="";
							//生成合并数据
							specList=new ArrayList<TestDTO2>();
							return Result.ok(list);
						}else {
							return Result.error("未能获取到方案，请手动填写");
						}
					}else {
						return Result.error("要合并的单据不满足相同物料、相同长度的条件");
					}
				}else {
					return Result.error("只有分切工序才能合并,请检查");
				}
			}else {
				return Result.error("未选择数据");
			}
		}
		return Result.ok("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param zrkQzOrderPage
	 * @return
	 */
	@AutoLog(value = "分切/切张单-编辑")
	@ApiOperation(value="分切/切张单-编辑", notes="分切/切张单-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ZrkQzOrderPage zrkQzOrderPage) {
		ZrkQzOrder zrkQzOrder = new ZrkQzOrder();
		BeanUtils.copyProperties(zrkQzOrderPage, zrkQzOrder);
		ZrkQzOrder zrkQzOrderEntity = zrkQzOrderService.getById(zrkQzOrder.getId());
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();//获取登录用户信息
		boolean flag = true;
		if(sysUser.getUsername().indexOf("admin")<0) {
			flag = false;
		}
		List<ErpSysRole> roleList = this.erpSysService.getRoleByUserId(sysUser.getId());
		if(null != roleList && roleList.size() > 0) {
			for (ErpSysRole erpSysRole : roleList) {
				if("productTeamLead".equals(erpSysRole.getRoleCode()) || "productLead".equals(erpSysRole.getRoleCode())) {
					flag = false;
					break;
				}
			}
		}
		ZrkQzOrder qzOrder = this.zrkQzOrderService.getById(zrkQzOrder.getId());
		boolean checkParamFlag = false;
		if(qzOrder.getIsFinish() == 0 && zrkQzOrder.getIsFinish() == 1) {
			checkParamFlag = true;
		}
		if(flag) {
			qzOrder.setIsFinish(zrkQzOrder.getIsFinish());
			zrkQzOrder = qzOrder;
		}
		if(checkParamFlag) {
			String orderProcessId = zrkQzOrder.getOrderProcessId();
			ZrkOrderProcess orderProcess = orderProcessService.getById(orderProcessId);
			String processCode = orderProcess.getProcessCode();
			ZrkParameters parameters = zrkParametersService.getByProcessCode(processCode);
			if(null == parameters) {
				return Result.error("请先输入生产参数。");
			}
		}
		//		if(zrkQzOrderEntity==null) {
		//			return Result.error("未找到对应数据");
		//		}

		if("3".equals(qzOrder.getMesOrderStatus())) {
			return Result.error("修改失败，MES单已经开始生产!");
		}else if("4".equals(qzOrder.getMesOrderStatus())){
			return Result.error("修改失败，MES单已经生产完成!");
		}else if("5".equals(qzOrder.getMesOrderStatus())){
			return Result.error("修改失败，MES单生产终止!");
		}

		zrkQzOrderService.updateMain(zrkQzOrder, zrkQzOrderPage.getZrkQzOrdeDetailList());

		return Result.ok("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "分切/切张单-通过id删除")
	@ApiOperation(value="分切/切张单-通过id删除", notes="分切/切张单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		zrkQzOrderService.delMain(id);
		return Result.ok("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "分切/切张单-批量删除")
	@ApiOperation(value="分切/切张单-批量删除", notes="分切/切张单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.zrkQzOrderService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "分切/切张单-通过id查询")
	@ApiOperation(value="分切/切张单-通过id查询", notes="分切/切张单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ZrkQzOrder zrkQzOrder = zrkQzOrderService.getById(id);
		if(zrkQzOrder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(zrkQzOrder);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "分切详情通过主表ID查询")
	@ApiOperation(value="分切详情主表ID查询", notes="分切详情-通主表ID查询")
	@GetMapping(value = "/queryZrkQzOrdeDetailByMainId")
	public Result<?> queryZrkQzOrdeDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<ZrkQzOrdeDetail> zrkQzOrdeDetailList = zrkQzOrdeDetailService.selectByMainId(id);
		return Result.ok(zrkQzOrdeDetailList);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param zrkQzOrder
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, ZrkQzOrder zrkQzOrder) {
		// Step.1 组装查询条件查询数据
		QueryWrapper<ZrkQzOrder> queryWrapper = QueryGenerator.initQueryWrapper(zrkQzOrder, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//Step.2 获取导出数据
		List<ZrkQzOrder> queryList = zrkQzOrderService.list(queryWrapper);
		// 过滤选中数据
		String selections = request.getParameter("selections");
		List<ZrkQzOrder> zrkQzOrderList = new ArrayList<ZrkQzOrder>();
		if(oConvertUtils.isEmpty(selections)) {
			zrkQzOrderList = queryList;
		}else {
			List<String> selectionList = Arrays.asList(selections.split(","));
			zrkQzOrderList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		}

		// Step.3 组装pageList
		List<ZrkQzOrderPage> pageList = new ArrayList<ZrkQzOrderPage>();
		for (ZrkQzOrder main : zrkQzOrderList) {
			ZrkQzOrderPage vo = new ZrkQzOrderPage();
			BeanUtils.copyProperties(main, vo);
			List<ZrkQzOrdeDetail> zrkQzOrdeDetailList = zrkQzOrdeDetailService.selectByMainId(main.getId());
			vo.setZrkQzOrdeDetailList(zrkQzOrdeDetailList);
			pageList.add(vo);
		}

		// Step.4 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "分切/切张单列表");
		mv.addObject(NormalExcelConstants.CLASS, ZrkQzOrderPage.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("分切/切张单数据", "导出人:"+sysUser.getRealname(), "分切/切张单"));
		mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		return mv;
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<ZrkQzOrderPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ZrkQzOrderPage.class, params);
				for (ZrkQzOrderPage page : list) {
					ZrkQzOrder po = new ZrkQzOrder();
					BeanUtils.copyProperties(page, po);
					zrkQzOrderService.saveMain(po, page.getZrkQzOrdeDetailList());
				}
				return Result.ok("文件导入成功！数据行数:" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(),e);
				return Result.error("文件导入失败:"+e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.ok("文件导入失败！");
	}

	/*--------------------------------子表处理-分切详情-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "分切详情-通过主表ID查询")
	@ApiOperation(value="分切详情-通过主表ID查询", notes="分切详情-通过主表ID查询")
	@GetMapping(value = "/listZrkQzOrdeDetailByMainId")
	public Result<?> listZrkQzOrdeDetailByMainId(ZrkQzOrdeDetail zrkQzOrdeDetail,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
			HttpServletRequest req) {
		//        QueryWrapper<ZrkQzOrdeDetail> queryWrapper = QueryGenerator.initQueryWrapper(zrkQzOrdeDetail, req.getParameterMap());
		String ids = zrkQzOrdeDetail.getZrkQzOrderId();
		StkPickUpBill pickUpBill = pickUpBillService.getById(ids);
		String mainId = UUID.randomUUID().toString();
		if(pickUpBill != null) {
			mainId = pickUpBill.getProcessId();
		}
		LambdaQueryWrapper<ZrkQzOrdeDetail> query = new LambdaQueryWrapper<>();
		query.eq(ZrkQzOrdeDetail::getZrkQzOrderId, mainId);
		query.orderByAsc(ZrkQzOrdeDetail::getId);
		Page<ZrkQzOrdeDetail> page = new Page<ZrkQzOrdeDetail>(pageNo, pageSize);
		IPage<ZrkQzOrdeDetail> pageList = zrkQzOrdeDetailService.page(page, query);
		return Result.ok(pageList);
	}

	/**
	 * 添加
	 * @param zrkQzOrdeDetail
	 * @return
	 */
	@AutoLog(value = "分切详情-添加")
	@ApiOperation(value="分切详情-添加", notes="分切详情-添加")
	@PostMapping(value = "/addZrkQzOrdeDetail")
	public Result<?> addZrkQzOrdeDetail(@RequestBody ZrkQzOrdeDetail zrkQzOrdeDetail) {
		zrkQzOrdeDetailService.save(zrkQzOrdeDetail);
		return Result.ok("添加成功！");
	}

	/**
	 * 编辑
	 * @param zrkQzOrdeDetail
	 * @return
	 */
	@AutoLog(value = "分切详情-编辑")
	@ApiOperation(value="分切详情-编辑", notes="分切详情-编辑")
	@PutMapping(value = "/editZrkQzOrdeDetail")
	public Result<?> editZrkQzOrdeDetail(@RequestBody ZrkQzOrdeDetail zrkQzOrdeDetail) {
		zrkQzOrdeDetailService.updateById(zrkQzOrdeDetail);
		return Result.ok("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "分切详情-通过id删除")
	@ApiOperation(value="分切详情-通过id删除", notes="分切详情-通过id删除")
	@DeleteMapping(value = "/deleteZrkQzOrdeDetail")
	public Result<?> deleteZrkQzOrdeDetail(@RequestParam(name="id",required=true) String id) {
		zrkQzOrdeDetailService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "分切详情-批量删除")
	@ApiOperation(value="分切详情-批量删除", notes="分切详情-批量删除")
	@DeleteMapping(value = "/deleteBatchZrkQzOrdeDetail")
	public Result<?> deleteBatchZrkQzOrdeDetail(@RequestParam(name="ids",required=true) String ids) {
		this.zrkQzOrdeDetailService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 导出
	 * @return
	 */
	@RequestMapping(value = "/exportZrkQzOrdeDetail")
	public ModelAndView exportZrkQzOrdeDetail(HttpServletRequest request, ZrkQzOrdeDetail zrkQzOrdeDetail) {
		// Step.1 组装查询条件
		QueryWrapper<ZrkQzOrdeDetail> queryWrapper = QueryGenerator.initQueryWrapper(zrkQzOrdeDetail, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<ZrkQzOrdeDetail> pageList = zrkQzOrdeDetailService.list(queryWrapper);
		List<ZrkQzOrdeDetail> exportList = null;

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "分切详情"); //此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, ZrkQzOrdeDetail.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("分切详情报表", "导出人:" + sysUser.getRealname(), "分切详情"));
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

	/**
	 * 导入
	 * @return
	 */
	@RequestMapping(value = "/importZrkQzOrdeDetail/{mainId}")
	public Result<?> importZrkQzOrdeDetail(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<ZrkQzOrdeDetail> list = ExcelImportUtil.importExcel(file.getInputStream(), ZrkQzOrdeDetail.class, params);
				for (ZrkQzOrdeDetail temp : list) {
					temp.setZrkQzOrderId(mainId);
				}
				long start = System.currentTimeMillis();
				zrkQzOrdeDetailService.saveBatch(list);
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.ok("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

	/*--------------------------------子表处理-分切详情-end----------------------------------------------*/

	/*--------------------------------子表处理-复合参数表-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "复合参数表-通过主表ID查询")
	@ApiOperation(value="复合参数表-通过主表ID查询", notes="复合参数表-通过主表ID查询")
	@GetMapping(value = "/listZrkParametersByMainId")
	public Result<?> listZrkParametersByMainId(ZrkParameters zrkParameters,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
			HttpServletRequest req) {
		//查询主表数据
//		ZrkQzOrder zqo=zrkQzOrderService.getById(zrkParameters.getProcessId());
		QueryWrapper<ZrkParameters> queryWrapper=QueryGenerator.initQueryWrapper(zrkParameters, req.getParameterMap());
		queryWrapper.eq("qz_order_id", zrkParameters.getQzOrderId());
		Page<ZrkParameters> page = new Page<ZrkParameters>(pageNo, pageSize);
		IPage<ZrkParameters> pageList = zrkParametersService.page(page, queryWrapper);
		return Result.ok(pageList);
	}



	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "复合参数表-通过主表ID查询")
	@ApiOperation(value="复合参数表-通过主表ID查询", notes="复合参数表-通过主表ID查询")
	@GetMapping(value = "/listZrkParametersByFH")
	public Result<?> listZrkParametersByFH(ZrkParameters zrkParameters,
										   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
										   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
										   HttpServletRequest req) {
//		String s=req.getParameter("materialId");
		//查询主表数据
//		ZrkQzOrder zqo=zrkQzOrderService.getById(zrkParameters.getProcessId());
        String orderId= zrkParameters.getQzOrderId();
        zrkParameters.setQzOrderId("");
		StringBuffer startDate = new StringBuffer();
		StringBuffer endDate = new StringBuffer();
		if(zrkParameters.getStartDate() != null && zrkParameters.getEndDate() != null){
			startDate.append(zrkParameters.getStartDate());
			startDate.append(" 00:00:00");
			zrkParameters.setStartDate(null);
			endDate.append(zrkParameters.getEndDate());
			endDate.append(" 23:59:59");
			zrkParameters.setEndDate(null);
		}
		QueryWrapper<ZrkParameters> queryWrapper=QueryGenerator.initQueryWrapper(zrkParameters, req.getParameterMap());
		if(startDate.length() > 0 && endDate.length() >0){
			queryWrapper.between("create_time",startDate.toString(),endDate.toString());
		}
		if(StringUtils.isNotBlank(orderId)) {
				ZrkQzOrder zrkQzOrder = zrkQzOrderService.getById(orderId);
				if(null!=zrkQzOrder) {
					queryWrapper.eq("material_Id", zrkQzOrder.getMaterialId());
			}
		}
		queryWrapper.eq("type", "1");
		Page<ZrkParameters> page = new Page<ZrkParameters>(pageNo, pageSize);
		IPage<ZrkParameters> pageList = zrkParametersService.page(page, queryWrapper);
		List<ZrkParameters> list = pageList.getRecords();
		for(ZrkParameters parameters:list) {
			ZrkQzOrder zrkQzOrder = zrkQzOrderService.getById(parameters.getQzOrderId());
			if(zrkQzOrder!=null) {
				parameters.setCustomerName(zrkQzOrder.getCustomerName());
				parameters.setFormulaId(zrkQzOrder.getFormulaId());
			}
		}
		pageList.setRecords(list);
		return Result.ok(pageList);
	}

	@AutoLog(value = "切张参数表")
	@ApiOperation(value="切张参数表", notes="切张参数表")
	@GetMapping(value = "/listZrkParametersByQZ")
	public Result<?> listZrkParametersByQZ(ZrkParameters zrkParameters,
										   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
										   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
										   HttpServletRequest req) {
		//查询主表数据
//		ZrkQzOrder zqo=zrkQzOrderService.getById(zrkParameters.getProcessId());
        String orderId= zrkParameters.getQzOrderId();
        zrkParameters.setQzOrderId("");
		StringBuffer startDate = new StringBuffer();
		StringBuffer endDate = new StringBuffer();
		if(zrkParameters.getStartDate() != null && zrkParameters.getEndDate() != null){
			startDate.append(zrkParameters.getStartDate());
			startDate.append(" 00:00:00");
			zrkParameters.setStartDate(null);
			endDate.append(zrkParameters.getEndDate());
			endDate.append(" 23:59:59");
			zrkParameters.setEndDate(null);
		}
		QueryWrapper<ZrkParameters> queryWrapper=QueryGenerator.initQueryWrapper(zrkParameters, req.getParameterMap());
		if(startDate.length() > 0 && endDate.length() >0){
			queryWrapper.between("create_time",startDate.toString(),endDate.toString());
		}
        if(StringUtils.isNotBlank(orderId)) {
				ZrkQzOrder zrkQzOrder = zrkQzOrderService.getById(orderId);
				if(null!=zrkQzOrder) {
					queryWrapper.eq("material_Id", zrkQzOrder.getMaterialId());
			}
		}
		queryWrapper.in("type","2");
		Page<ZrkParameters> page = new Page<ZrkParameters>(pageNo, pageSize);
		IPage<ZrkParameters> pageList = zrkParametersService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	@AutoLog(value = "分切参数表")
	@ApiOperation(value="分切参数表", notes="分切参数表")
	@GetMapping(value = "/listZrkParametersByFQ")
	public Result<?> listZrkParametersByFQ(ZrkParameters zrkParameters,
											   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
											   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
											   HttpServletRequest req) {
		//查询主表数据
//		ZrkQzOrder zqo=zrkQzOrderService.getById(zrkParameters.getProcessId());
        String orderId= zrkParameters.getQzOrderId();
        zrkParameters.setQzOrderId("");
		StringBuffer startDate = new StringBuffer();
		StringBuffer endDate = new StringBuffer();
		if(zrkParameters.getStartDate() != null && zrkParameters.getEndDate() != null){
			startDate.append(zrkParameters.getStartDate());
			startDate.append(" 00:00:00");
			zrkParameters.setStartDate(null);
			endDate.append(zrkParameters.getEndDate());
			endDate.append(" 23:59:59");
			zrkParameters.setEndDate(null);
		}
		QueryWrapper<ZrkParameters> queryWrapper=QueryGenerator.initQueryWrapper(zrkParameters, req.getParameterMap());
		if(startDate.length() > 0 && endDate.length() >0){
			queryWrapper.between("create_time",startDate.toString(),endDate.toString());
		}
        if(StringUtils.isNotBlank(orderId)) {
				ZrkQzOrder zrkQzOrder = zrkQzOrderService.getById(orderId);
				if(null!=zrkQzOrder) {
					queryWrapper.eq("material_Id", zrkQzOrder.getMaterialId());
			}
		}
		queryWrapper.eq("type", "3");
		Page<ZrkParameters> page = new Page<ZrkParameters>(pageNo, pageSize);
		IPage<ZrkParameters> pageList = zrkParametersService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	/**
	 * 添加
	 * @param zrkParameters
	 * @return
	 */
	@AutoLog(value = "复合参数表-添加")
	@ApiOperation(value="复合参数表-添加", notes="复合参数表-添加")
	@PostMapping(value = "/addZrkParameters")
	public Result<?> addZrkParameters(@RequestBody ZrkParametersVO zrkParameters) {
		//查询主表数据
		ZrkQzOrder zrkQzOrder=zrkQzOrderService.getById(zrkParameters.getProcessId());
		//查询当前用户
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String userId = sysUser.getId();
		ZrkParameters zrkParameters1=new ZrkParameters();
		if(null!=zrkQzOrder) {
			BeanUtils.copyProperties(zrkParameters,zrkParameters1);
			List<String> fhPlanenessList = zrkParameters.getFhPlaneness();
			if(CollUtil.isNotEmpty(fhPlanenessList)) {
				zrkParameters1.setFhPlaneness(CollUtil.join(fhPlanenessList, ","));
			}
			zrkParameters1.setProcessId(zrkQzOrder.getProcessId());
			zrkParameters1.setMaterialId(zrkQzOrder.getMaterialId());
			zrkParameters1.setMachineId(zrkQzOrder.getMachineId());
			zrkParameters1.setUserId(userId);
			zrkParameters1.setQzOrderId(zrkQzOrder.getId());
		}else {
			return Result.error("未找到切张单数据");
		}
		zrkParametersService.save(zrkParameters1);
		if(zrkQzOrder.getProcessId().equals(MaterialConstant.PROCESS_CUTTING_BIG)||
				zrkQzOrder.getProcessId().equals(MaterialConstant.PROCESS_CUTTING_NORMAL)){
			zrkQzOrderService.changeOrderStatus(zrkQzOrder.getId(), "4",zrkParameters.getUserIds());
		}else{
			zrkQzOrderService.changeOrderStatus(zrkQzOrder.getId(), "4",null);
		}
		LambdaQueryWrapper<StkIoBill> query = new LambdaQueryWrapper<StkIoBill>();
		query.eq(StkIoBill::getSourceId, zrkQzOrder.getId());
		query.likeRight(StkIoBill::getStockIoType, "1");
		List<StkIoBill> stkIoBillList = stkIoBillService.list(query);
		List<String> materialCodeList = Lists.newArrayList();
		if(stkIoBillList!=null&&stkIoBillList.size()>0) {
			List<String> ioBillIdList = Lists.newArrayList();
			for(StkIoBill stkIoBill:stkIoBillList) {
				ioBillIdList.add(stkIoBill.getId());
			}
			List<StkIoBillEntry> entryList = stkIoBillEntryMapper.selectBatchByMainIdList(ioBillIdList);
			if(entryList!=null&&entryList.size()>0) {
				List<String> materialIdList = Lists.newArrayList();
				for(StkIoBillEntry stkIoBillEntry:entryList) {
					materialIdList.add(stkIoBillEntry.getMaterialId());
				}
				List<BasMaterial> materialList = basMaterialService.getByIds(materialIdList);
				if(materialList!=null&&materialList.size()>0) {
					for(BasMaterial basMaterial:materialList) {
						materialCodeList.add(basMaterial.getCode());
					}
				}
			}
		}
		LambdaQueryWrapper<BasMaterialTemp> queryWrapper = new LambdaQueryWrapper<BasMaterialTemp>();
		queryWrapper.eq(BasMaterialTemp::getOrderId, zrkQzOrder.getId());
		List<BasMaterialTemp> tempList = basMaterialTempService.list(queryWrapper);
		List<String> codeList = Lists.newArrayList();
		StringBuffer buffer = new StringBuffer();
		if(tempList!=null&&tempList.size()>0) {
			for(BasMaterialTemp temp:tempList) {
				if(!materialCodeList.contains(temp.getCode())) {
					buffer.append(temp.getCode());
					buffer.append(",");
					codeList.add(temp.getCode());
				}
			}
			if(codeList!=null && codeList.size()>0) {
				return Result.ok("mes单编号为："+ zrkQzOrder.getCode() +"，物料编号为："+ buffer.toString() +"的物料尚未入库，请及时入库");
			}else {
				return Result.ok("mes单编号为："+ zrkQzOrder.getCode() +"的物料已全部入库");
			}
		}
		if(StringUtils.equals("1300701063685087234", zrkQzOrder.getProcessId())
				|| StringUtils.equals("1300701144731623426", zrkQzOrder.getProcessId())
				|| StringUtils.equals("1300701196116041729", zrkQzOrder.getProcessId())) {
			basApi.sendProductedMessage(zrkParameters.getProcessId());
		}
		return Result.ok("生产完成");
	}

	/**
	 * 编辑
	 * @param zrkParameters
	 * @return
	 */
	@AutoLog(value = "复合参数表-编辑")
	@ApiOperation(value="复合参数表-编辑", notes="复合参数表-编辑")
	@PutMapping(value = "/editZrkParameters")
	public Result<?> editZrkParameters(@RequestBody ZrkParameters zrkParameters) {
		//查询主表数据
		ZrkQzOrder zrkQzOrder=zrkQzOrderService.getById(zrkParameters.getProcessId());
		if(null!=zrkQzOrder) {
			zrkParameters.setProcessId(zrkQzOrder.getProcessId());
		}else {
			return Result.error("未找到切张单数据");
		}
		zrkParametersService.updateById(zrkParameters);
		return Result.ok("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "复合参数表-通过id删除")
	@ApiOperation(value="复合参数表-通过id删除", notes="复合参数表-通过id删除")
	@DeleteMapping(value = "/deleteZrkParameters")
	public Result<?> deleteZrkParameters(@RequestParam(name="id",required=true) String id) {
		zrkParametersService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "复合参数表-批量删除")
	@ApiOperation(value="复合参数表-批量删除", notes="复合参数表-批量删除")
	@DeleteMapping(value = "/deleteBatchZrkParameters")
	public Result<?> deleteBatchZrkParameters(@RequestParam(name="ids",required=true) String ids) {
		this.zrkParametersService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 导出
	 * @return
	 */
	@RequestMapping(value = "/exportZrkParameters")
	public ModelAndView exportZrkParameters(HttpServletRequest request, ZrkParameters zrkParameters) {
		// Step.1 组装查询条件
		QueryWrapper<ZrkParameters> queryWrapper = QueryGenerator.initQueryWrapper(zrkParameters, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<ZrkParameters> pageList = zrkParametersService.list(queryWrapper);
		List<ZrkParameters> exportList = null;

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "复合参数表"); //此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, ZrkParameters.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("复合参数表报表", "导出人:" + sysUser.getRealname(), "复合参数表"));
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

	/**
	 * 导入
	 * @return
	 */
	@RequestMapping(value = "/importZrkParameters/{mainId}")
	public Result<?> importZrkParameters(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<ZrkParameters> list = ExcelImportUtil.importExcel(file.getInputStream(), ZrkParameters.class, params);
				for (ZrkParameters temp : list) {
					temp.setProcessId(mainId);
				}
				long start = System.currentTimeMillis();
				zrkParametersService.saveBatch(list);
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.ok("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

	/*--------------------------------子表处理-复合参数表-end----------------------------------------------*/
	@GetMapping(value = "/queryResult")
	public Result<?> queryResult(RequestInfo ri) {
		String res=RemoteUtils.makePostCall(ri, ri.getId());
		return Result.ok(res);
	}
	
	@PostMapping("/seperateMes")
	public Result<?> seperateMes(@RequestBody SeperateMesVO seperateMesVO){
		
		return null;
	}
	
	/**
	 * @Description 修改Mes单状态为生产中
	 * @param id
	 * @return
	 * Create at: 2021-01-07 16:05:44
	 * @author: duany
	 * Revision:
	 *    2021-01-07 16:05:44 - first revision by duany
	 *        
	 */
	@GetMapping("/changeStatusToProducing")
	public Result<?> changeStatusToProducing(@RequestParam("id")String id){
		List<MaterialDTO> list = this.zrkQzOrderService.getMesMaterial(id);
		if(list==null||list.size()==0) {
			return Result.error("物料未出库，不可开始生产");
		}
		List<StkPickUpBill> stkPickUpBills=pickUpBillService.getByMesId(id);
		List<String> materials=zrkQzOrderService.getMesMaterials(id);
		if(stkPickUpBills!=null && stkPickUpBills.size()>0){
			for (StkPickUpBill stkPickUpBill : stkPickUpBills) {
				List<StkPickUpEntry> stkPickUpEntries=pickUpEntryService.getByBillId(stkPickUpBill.getId());
				for (StkPickUpEntry stkPickUpEntry : stkPickUpEntries) {
					if(materials ==null){
						return Result.error("没有物料出库，请确认提货");
					}
					if(	!materials.contains(stkPickUpEntry.getCategoryId())){
						return Result.error("物料出库不全，请确认提货物料");
					}
				}
			}
		}
		boolean flag = this.zrkQzOrderService.changeStatusToProducing(id);
		if(!flag) {
			return Result.error("修改失败");
		}
		return Result.ok("修改成功");
	}
	
	/**
	 * @Description 修改mes单状态为完成
	 * @param id
	 * @return
	 * Create at: 2021-01-18 09:55:39
	 * @author: duany
	 * Revision:
	 *    2021-01-18 09:55:39 - first revision by duany
	 *        
	 */
	@GetMapping("/changeStatusToComplete")
	public Result<?> changeStatusToComplete(@RequestParam("id")String id){
		boolean flag = this.zrkQzOrderService.changeOrderStatus(id, "4",null);
		if(!flag) {
			return Result.error("修改失败");
		}
		return Result.ok("修改成功");
	}
	
	/**
	 * @Description 中止MES单
	 * @param id
	 * @return
	 * Create at: 2021-01-18 09:55:39
	 * @author: duany
	 * Revision:
	 *    2021-01-18 09:55:39 - first revision by duany
	 *        
	 */
	@GetMapping("/changeStatusToDiscontinue")
	public Result<?> changeStatusToDiscontinue(@RequestParam("id")String id){
		boolean flag = this.zrkQzOrderService.changeOrderStatus(id, "5",null);
		if(!flag) {
			return Result.error("修改失败");
		}
		return Result.ok("修改成功");
	}
	
	/**
	 * @Description 查看该mes单出库的物料
	 * @param id
	 * @return
	 * Create at: 2021-01-18 09:58:07
	 * @author: duany
	 * Revision:
	 *    2021-01-18 09:58:07 - first revision by duany
	 *        
	 */
	@GetMapping("/getMesMaterial")
	public Result<List<MaterialDTO>> getMesMaterial(@RequestParam("id")String id){
		Result<List<MaterialDTO>> result = new Result<>();
		if(oConvertUtils.isEmpty(id)) {
			result.setSuccess(Boolean.FALSE);
			result.setCode(CommonConstant.SC_INTERNAL_SERVER_ERROR_500);
			return result;
		}
		List<MaterialDTO> list = this.zrkQzOrderService.getMesMaterial(id);
		result.setCode(CommonConstant.SC_OK_200);
		result.setSuccess(Boolean.TRUE);
		if(list!=null&&list.size()>0) {
			result.setResult(list);
			return result;
		}else {
			list = Lists.newArrayList();
		}
		result.setResult(list);
		
		return result;
	}
	
	
	@GetMapping("/getQZPrint")
	public Result<PrintQzOrderVO> getQZPrint(@RequestParam("id")String id){
		ZrkQzOrder zrk = this.zrkQzOrderService.getById(id);
		Result<PrintQzOrderVO> result = new Result<>();
		if(zrk!=null) {
			PrintQzOrderVO printQzOrderVO = new PrintQzOrderVO();
			printQzOrderVO.setCode(zrk.getCode());
			printQzOrderVO.setCustomerName(zrk.getCustomerName());
			BasMaterialCategory materialCategory = basMaterialCategoryService.getById(zrk.getMaterialId());
			if(materialCategory==null) {
				printQzOrderVO.setMaterialName("");
			}else {
				printQzOrderVO.setMaterialName(materialCategory.getName());
			}
			printQzOrderVO.setProductNum(zrk.getProductNum());
			printQzOrderVO.setRemark(zrk.getRemark());
			printQzOrderVO.setSpecs(zrk.getSpecs());
			if(oConvertUtils.isNotEmpty(zrk.getOrderProcessId())) {
				ZzShoporder shoporder = orderService.getById(zrk.getOrderProcessId());
				printQzOrderVO.setWoPlanendtime(shoporder.getWoPlanendtime());
			}
			result.setCode(CommonConstant.SC_OK_200);
			result.setSuccess(Boolean.TRUE);
			result.setResult(printQzOrderVO);
		}
		return result;
	}
	
	@GetMapping("/updateQZPrintStatus")
	public Result<ZrkQzOrder> updateQZPrintStatus(@RequestParam("id")String id){
		Result<ZrkQzOrder> result = new Result<>();
		ZrkQzOrder zrk = this.zrkQzOrderService.getById(id);
		if(zrk==null) {
			result.setMessage("未找到mes单");
			result.setSuccess(false);
			return result;
		}
		zrk.setIsPrint(1);
		zrkQzOrderService.updateById(zrk);
		result.setMessage("修改成功");
		result.setSuccess(true);
		return result;
	}
	
	/**
	 *mes单直接修改操作人及机器
	 *
	 * @param zrkQzOrderPage
	 * @return
	 */
	@AutoLog(value = "mes单直接修改操作人及机器")
	@ApiOperation(value="mes单直接修改操作人及机器", notes="mes单直接修改操作人及机器")
	@PutMapping(value = "/editUserAndMachine")
	public Result<?> editUserAndMachine(@RequestBody ZrkQzOrder zrkQzOrder) {
		return this.zrkQzOrderService.updateUserAndMachine(zrkQzOrder);
	}
}
